﻿
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Utils
{
    public static class StringHelper
    {

        //public static bool MatchAga(this string str, string keyword, params string[] keys)
        //{
        //    return true;
        //}


        public static int FindInSet(this string strList, object ch)
        {
            if (strList == null) return -1;
            return new List<string>(strList.Split(',')).IndexOf(ch.ToString());
        }

        public static string IfNullOrEmpty(this string str, string defaultValue = "", string packageFormat = null)
        {
            return string.IsNullOrEmpty(str) ? defaultValue : (string.IsNullOrEmpty(packageFormat) ? str : string.Format(packageFormat, str));
        }


        public static string IfNullOrEmpty(this string str, Func<string> defaultValue)
        {
            return string.IsNullOrEmpty(str) ? defaultValue?.Invoke() : str;
        }


        /// <summary>
        /// UrlEncode Url编码
        /// </summary>
        /// <param name="str">待编码字符串</param>
        /// <param name="encoding">编码规则</param>
        /// <returns>编码后的字符串</returns>
        public static string UrlEncode(this string str, Encoding encoding)
        {
            if (string.IsNullOrEmpty(str))
            {
                return str;
            }
            return HttpUtility.UrlEncode(str, encoding);
        }
        /// <summary>
        /// UrlEncode Url编码,默认UTF-8编码
        /// </summary>
        /// <param name="str">待编码字符串</param>
        /// <returns>编码后的字符串</returns>
        public static string UrlEncode(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return str;
            }
            return str.UrlEncode(Encoding.UTF8);
        }

        /// <summary>
        /// UrlDecode Url解码
        /// </summary>
        /// <param name="str">待解码字符串</param>
        /// <param name="encoding">解码规则</param>
        /// <returns>解码后的字符串</returns>
        public static string UrlDecode(this string str, Encoding encoding)
        {
            if (string.IsNullOrEmpty(str))
            {
                return str;
            }
            return HttpUtility.UrlDecode(str, encoding);
        }
        /// <summary>
        /// UrlDecode Url解码,默认UTF-8编码
        /// </summary>
        /// <param name="str">待解码字符串</param>
        /// <returns>解码后的字符串</returns>
        public static string UrlDecode(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return str;
            }
            return str.UrlDecode(Encoding.UTF8);
        }

        public static IDictionary<string, string> LoadConfig(string configStr)
        {
            var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            if (configStr == null)
            {
                return dict;
            }
            var configs = configStr.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var config in configs)
            {
                int index = config.IndexOf(':');
                if (index >= 0)
                {
                    dict.Add(config[..index].Trim(), config[(index + 1)..].Trim());
                }
            }
            return dict;
        }
        public static string SubstringByte(this string text, int startIndex, int length)
        {
            return SubstringByte(text, startIndex, length, Encoding.UTF8);
        }

        public static string SubstringByte(this string text, int startIndex, int length, Encoding _encoding)
        {
            if (text == null) return null;
            byte[] bytes = _encoding.GetBytes(text);
            return _encoding.GetString(bytes, startIndex, Math.Min(bytes.Length - startIndex, length));
        }
        #region 移除所有HTML标记
        /// <summary>
        /// 移除所有HTML标记
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveHtml(this string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return string.Empty;
            }
            const string regexstr = @"<[^>]*>";
            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }
        #endregion

        #region 移除不可见字符
        /// <summary>
        /// 移除不可见字符
        /// </summary>
        /// <param name="str">待操作字符串</param>
        /// <returns></returns>
        public static string RemoveInvisibleChar(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return str;
            }
            var sb = new System.Text.StringBuilder(131);
            for (int i = 0; i < str.Length; i++)
            {
                int Unicode = str[i];
                if (Unicode >= 16)
                {
                    sb.Append(str[i].ToString());
                }
            }
            return sb.ToString();
        }
        #endregion

        #region 提取网页图片地址

        /// <summary>
        /// 提取网页图片地址
        /// </summary>
        /// <param name="sHtmlText"></param>
        /// <returns></returns>
        public static string[] GetHtmlImageUrlList(string sHtmlText)
        {
            if (string.IsNullOrEmpty(sHtmlText)) return new string[0];
            // 定义正则表达式用来匹配 img 标签   
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串   
            MatchCollection matches = regImg.Matches(sHtmlText);
            int i = 0;
            string[] sUrlList = new string[matches.Count];

            // 取得匹配项列表   
            foreach (Match match in matches)
                sUrlList[i++] = match.Groups["imgUrl"].Value;
            return sUrlList;
        }

        #endregion

        #region 隐藏手机号和邮箱的中间部分
        /// <summary>
        /// 获取隐藏中间数字的手机号码
        /// </summary>
        /// <param name="mobile">手机号码</param>
        /// <returns></returns>
        public static string HideMobile(string mobile)
        {
            if (!string.IsNullOrEmpty(mobile) && mobile.Length > 10)
            {
                return string.Format("{0}*****{1}", mobile.Substring(0, 3), mobile.Substring(mobile.Length - 3, 3));
            }
            else return mobile;
        }

        /// <summary>
        /// 获得隐藏部分邮箱名称后的Email地址
        /// </summary>
        /// <param name="email">Email地址</param>
        /// <returns></returns>
        public static string HideEmail(string email)
        {
            if (string.IsNullOrEmpty(email))
            {
                return string.Empty;
            }
            if (email.IndexOf("@") > 0)
            {
                string name = email.Split('@')[0];
                string host = email.Split('@')[1];
                return string.Format("{0}***{1}@{2}", name.Substring(0, 1), name.Substring(name.Length - 1, 1), host);
            }
            else return email;
        }
        #endregion


        #region 静态私有变量
        /// <summary>
        /// 需要转义的字符正则
        /// </summary>
        static readonly Regex _transferredRule = new Regex(@"('|""|\\)", RegexOptions.Compiled);
        /// <summary>
        /// 数字
        /// </summary>
        static readonly string[] numArray = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        /// <summary>
        /// 字母
        /// </summary>
        static readonly string[] letterArray = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "X" };
        /// <summary>
        /// 数字与字母混合
        /// </summary>
        static readonly string[] numberAndLetterArray = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "X" };
        #endregion

        #region 随机字符串类型


        /// <summary>
        /// 生成一个随机不重复的字符串，用于文件命名
        /// </summary>
        /// <returns>返回</returns>
        public static string RadomFileName()
        {
            return DateTime.Now.ToFileTime().ToString() + GetRandomNext(3);
        }

        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private static int GetRandomNext(int length)
        {
            Guid gu = Guid.NewGuid();
            string str = "";
            for (int i = 0; i < gu.ToString().Length; i++)
            {
                if (ValidatorHelper.IsInteger(gu.ToString()[i].ToString()))
                {
                    str += ((gu.ToString()[i]));
                }
            }
            int guid = int.Parse(str.Replace("-", "").Substring(0, length));
            if (!guid.ToString().Length.Equals(length))
                guid = GetRandomNext(length);
            return guid;
        }

        /// <summary>
        /// 获取随机字符串
        /// </summary>
        /// <param name="length">字符串长度</param>
        /// <param name="randCodeType">字符类型</param>
        /// <returns>返回生成的字符串</returns>
        public static string GetRandomCode(int length, RandCodeType randCodeType)
        {
            StringBuilder strb = new StringBuilder();
            long tick = DateTime.Now.Ticks;
            Random rnd = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
            int randcodeType = (int)randCodeType;

            for (int i = 0; i < length; i++)
            {
                switch (randcodeType)
                {
                    case 1:
                        strb.Append(numArray[rnd.Next(0, numArray.Length)]); break;
                    case 2:
                        strb.Append(letterArray[rnd.Next(0, letterArray.Length)]); break;
                    case 3:
                        strb.Append(numberAndLetterArray[rnd.Next(0, numberAndLetterArray.Length)]); break;
                }
            }

            return strb.ToString();
        }
        #endregion
    }
    /// <summary>
    /// 随机字符串类型
    /// </summary>
    [Flags]
    public enum RandCodeType
    {
        /// <summary>
        /// 仅数字
        /// </summary>
        NUMBER = 1,
        /// <summary>
        /// 字母
        /// </summary>
        LETTER = 2,

    }
}
